package com.web.kftsdk.common.util;

import java.lang.reflect.Field;

/**
 * <p>Title: BeanUtil</p>
 * <p>Description: TODO</p>
 *
 * @author xukk
 * @version 1.0
 * @date 2018/6/14
 */
public class BeanUtil {
    /**
     * 获取当前类声明的private/protected变量
     */
    static public Object getFieldValue(Object object, String propertyName)
            throws IllegalAccessException, NoSuchFieldException {
        Field field = object.getClass().getDeclaredField(propertyName);
        field.setAccessible(true);

        return field.get(object);
    }

    /**
     * zhangpf :因为getFieldValue()方法，无法读取super class的属性的值；
     * 所以本方法做出扩展，允许读取super class的属性的值；
     *
     * @param object
     * @param propertyName
     * @return
     * @throws IllegalAccessException
     * @throws NoSuchFieldException
     */
    public static Object getFieldValueInAllSuper(Object object, String propertyName)
            throws IllegalAccessException, NoSuchFieldException {
        Class claszz = object.getClass();
        Field field = null;

        do {
            try {
                field = claszz.getDeclaredField(propertyName);
            } catch (NoSuchFieldException e) {
                field = null;
            }
            claszz = claszz.getSuperclass();
        }
        while (field == null && claszz != null);

        if (field == null) {
            return null;
        }

        field.setAccessible(true);
        return field.get(object);
    }
}
